#include "console.h"
#include "../sys/sys_output.h"

#include <stdio.h>
#include <stdarg.h>
#include <time.h>

static bool consoleOpen=false;


void con_init()
{
	if (consoleOpen)
		return;

	FILE *f=fopen(CONSOLE_FILE,"wt");
	consoleOpen = (f != NULL);
	fclose(f);

	sys_createConsoleWindow();
	con_output("Console started\n");
}

void con_error(int level, const char* format, ...)
{
	va_list ap;
	char msg[2048];

	va_start(ap, format);
	vsprintf(msg, format, ap);
	va_end(ap);
	con_output(msg);

	if (level == CONSOLE_FATAL)
	{
		sys_ErrorMessage(msg);	
	}
}

void con_printf(const char* format, ... )
{
	va_list ap;
	char msg[2048];

	va_start(ap, format);
	vsprintf(msg, format, ap);
	va_end(ap);
	con_output(msg);
}

void con_output(const char* str)
{
	con_init();
	FILE *f = fopen(CONSOLE_FILE, "at");
	if (!f) return;

	time_t rawtime;
	struct tm * timeinfo;
	time (&rawtime);
	timeinfo = localtime(&rawtime);
	char buffer [128];

	strftime (buffer,128,"[%d/%m/%Y %H:%M:%S]  ", timeinfo);

	fprintf(f, "%s%s\n", buffer, str);
	fclose(f);
	sys_addConsoleWindowText(buffer, str);
}